package dk.eclipse.android.badassapp.sensor.proximity;

import java.util.List;

import dk.eclipse.android.badassapp.sensor.SensorActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 */
public class ProximityManager {

	private static Sensor sensor;
	private static SensorManager sensorManager;
	private static ProximityListener listener;

	/** indicates whether or not the sensor is supported */
	private static Boolean supported;
	/** indicates whether or not the sensor is running */
	private static boolean running = false;

	/**
	 * Returns true if the manager is listening to changes
	 */
	public static boolean isListening() {
		return running;
	}

	/**
	 * Unregisters listeners
	 */
	public static void stopListening() {
		running = false;
		try {
			if (sensorManager != null && sensorEventListener != null) {
				sensorManager.unregisterListener(sensorEventListener);
			}
		} catch (Exception e) {
		}
	}

	/**
	 * Returns true if at least one sensor is available
	 */
	public static boolean isSupported() {

		if (supported == null) {
			Context context = SensorActivity.getContext();
			if (context != null) {
				sensorManager = (SensorManager) context
						.getSystemService(Context.SENSOR_SERVICE);
				List<Sensor> sensors = sensorManager
						.getSensorList(Sensor.TYPE_PROXIMITY);
				supported = new Boolean(sensors.size() > 0);
			} else {
				supported = Boolean.FALSE;
			}
		}
		return supported;
	}

	/**
	 * Registers a listener and start listening
	 * 
	 * @param proximityListener
	 *            callback for events
	 */
	public static void startListening(ProximityListener proximityListener) {

		Context context = SensorActivity.getContext();

		sensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		List<Sensor> sensors = sensorManager
				.getSensorList(Sensor.TYPE_PROXIMITY);
		if (sensors.size() > 0) {
			sensor = sensors.get(0);
			running = sensorManager.registerListener(sensorEventListener,
					sensor, SensorManager.SENSOR_DELAY_GAME);
			listener = proximityListener;
		}
	}

	/**
	 * The listener that listen to events
	 */
	private static SensorEventListener sensorEventListener = new SensorEventListener() {

		private float proximity = 0;

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}

		public void onSensorChanged(SensorEvent event) {

			proximity = event.values[0];

			// trigger change event
			listener.onProximityChanged(proximity);
		}

	};

}